<script lang="ts">
import { defineComponent, ref } from 'vue'
import { useVersionStore } from './stores/versionStore'
import { useLLMStore } from './stores/llmStore'
import { useEvaluationStore } from './stores/evaluation'
import EvalTaskGenerator from './components/EvalTaskGenerator.vue'

export default defineComponent({
  components: {
    EvalTaskGenerator
  },
  setup() {
    const versionStore = useVersionStore()
    const llmStore = useLLMStore()
    const evaluationStore = useEvaluationStore()
    const expandedGroups = ref({
      data: true,
      operations: true,
      evaluation: true
    })
    const newVersion = ref({
      baseVer: '',
      newVer: '',
      description: ''
    })
    const errorMessage = ref('')
    const showError = ref(false)

    const toggleGroup = (group: string) => {
      expandedGroups.value[group] = !expandedGroups.value[group]
    }

    const toggleLLMDialog = () => {
      llmStore.toggleLLMDialog()
    }

    const toggleEvaluationCreator = (show: boolean) => {
      evaluationStore.toggleEvaluationCreator(show)
      // 当关闭时清空已选问题
      if (!show) {
        evaluationStore.selectedQuestionIds = []
      }
    }

    return {
      versionStore,
      llmStore,
      evaluationStore,
      expandedGroups,
      toggleGroup,
      toggleEvaluationCreator,
      toggleLLMDialog,
      newVersion,
      handleCreateVersion: async () => {
        try {
          console.log('新版本创建请求:', newVersion.value)
          const response = await versionStore.addNewVersion(
            newVersion.value.baseVer,
            newVersion.value.newVer,
            newVersion.value.description
          )
          
          console.log('创建版本成功响应:', response)
          
          newVersion.value = {
            baseVer: '',
            newVer: '',
            description: ''
          }
          versionStore.showVersionCreator = false
        } catch (error) {
          // 断言 error 为 any 类型以便访问 response/request
          const err = error as any
          if (err.response) {
            // 请求已发出且服务器响应状态码不在2xx范围内
            console.error('创建版本失败 - 服务器响应:', {
              status: err.response.status,
              data: err.response.data,
              headers: err.response.headers,
              config: err.response.config
            })
            errorMessage.value = err.response.data?.message || 
                               err.response.data?.error || 
                               JSON.stringify(err.response.data)
          } else if (err.request) {
            // 请求已发出但没有收到响应
            console.error('创建版本失败 - 无响应:', err.request)
            errorMessage.value = '服务器无响应，请检查网络连接'
          } else {
            // 发送请求时出错
            const errMsg = (err as any).message || '未知错误'
            console.error('创建版本失败 - 请求错误:', errMsg)
            errorMessage.value = errMsg
          }
          showError.value = true
        }
      },
      errorMessage,
      showError,
      handlePublishVersion: async () => {
        try {
          await versionStore.publishCurrentVersion()
          // 发布成功后刷新页面
          window.location.reload()
        } catch (error) {
          const err = error as any
          if (err.response) {
            errorMessage.value = err.response.data?.message || 
                               err.response.data?.error || 
                               '发布版本失败'
          } else {
            errorMessage.value = err.message || '发布版本失败'
          }
          showError.value = true
        }
      }
    }
  }
})
</script>

<template>
  <div class="app-container">
    <aside class="app-sidebar">
      <div class="sidebar-header">
        <h3>数据管理</h3>
        <div class="version-selector">
          <span class="label">版本:</span>
          <select 
            v-if="versionStore.currentVersion && versionStore.versions.length"
            :value="versionStore.currentVersion?.ver_code"
            @change="e => {
              const selected = versionStore.versions.find(v => v.ver_code === e.target.value)
              if (selected) versionStore.setVersion(selected)
            }"
          >
            <option 
              v-for="v in versionStore.versions" 
              :key="v.ver_code" 
              :value="v.ver_code"
            >
              {{ v.ver_code }}
            </option>
          </select>
          <span v-else class="loading">加载中...</span>
          <button 
            class="version-action-btn publish-version-btn"
            @click="handlePublishVersion"
            :disabled="!versionStore.currentVersion || versionStore.loading"
            :title="versionStore.currentVersion ? '发布当前版本' : '请先选择版本'"
          >
            <span>发布</span>
          </button>
          <button 
            class="version-action-btn new-version-btn" 
            @click="versionStore.showVersionCreator = true"
            title="创建新版本"
          >
            <span>创建新版本</span>
          </button>
        </div>
      </div>
      <nav class="sidebar-nav">
        <router-link to="/" class="nav-item">
          <span class="icon">🏠</span>
          <span class="text">主页</span>
        </router-link>
        
        <div class="nav-group">
          <div class="nav-header" @click="toggleGroup('data')">
            <span class="icon">📊</span>
            <span class="text">数据管理</span>
            <span class="arrow">{{ expandedGroups.data ? '▼' : '▶' }}</span>
          </div>
          <div v-show="expandedGroups.data" class="nav-subitems">
            <router-link to="/question-management" class="nav-subitem">
              <span class="icon">📋</span>
              <span class="text">原始问题管理</span>
            </router-link>
            <router-link to="/standard-management" class="nav-subitem">
              <span class="icon">📑</span>
              <span class="text">标准问题管理</span>
            </router-link>
          </div>
        </div>
        
        <div class="nav-group">
          <div class="nav-header" @click="toggleGroup('evaluation')">
            <span class="icon">🔧</span>
            <span class="text">评测工具</span>
            <span class="arrow">{{ expandedGroups.evaluation ? '▼' : '▶' }}</span>
          </div>
          <div v-show="expandedGroups.evaluation" class="nav-subitems">
            <!-- <div class="nav-subitem" @click="toggleLLMDialog">
              <span class="icon">🤖</span>
              <span class="text">大模型回答生成</span>
            </div> -->
            <!-- <router-link to="/llm-answers" class="nav-subitem">
              <span class="icon">📝</span>
              <span class="text">大模型回答管理</span>
            </router-link> -->
            <router-link to="/evaluation" class="nav-subitem">
              <span class="icon">📊</span>
              <span class="text">评测任务管理</span>
            </router-link>
            <div 
              class="nav-subitem" 
              @click="toggleEvaluationCreator(true)"
            >
              <span class="icon">🛠️</span>
              <span class="text">创建评测任务</span>
            </div>
          </div>
        </div>
      </nav>
    </aside>
    <main class="app-content">
      <RouterView />
      <EvalTaskGenerator v-if="evaluationStore.showEvaluationCreator" />
      
      <!-- 错误提示 -->
      <div v-if="showError" class="error-alert">
        <div class="error-content">
          <span>{{ errorMessage }}</span>
          <button @click="showError = false" class="close-btn">×</button>
        </div>
      </div>

      <!-- 新建版本模态框 -->
      <div v-if="versionStore.showVersionCreator" class="modal-overlay">
        <div class="modal-content">
          <h3>新建版本</h3>
          <form @submit.prevent="handleCreateVersion">
            <div class="form-group">
              <label>基础版本</label>
              <select v-model="newVersion.baseVer">
                <option value="">无</option>
                <option 
                  v-for="v in versionStore.versions" 
                  :key="v.ver_code" 
                  :value="v.ver_code"
                >
                  {{ v.ver_code }}
                </option>
              </select>
            </div>
            <div class="form-group">
              <label>新版本号</label>
              <input v-model="newVersion.newVer" required />
            </div>
            <div class="form-group">
              <label>描述</label>
              <textarea v-model="newVersion.description" rows="3"></textarea>
            </div>
            <div class="form-actions">
              <button 
                type="button" 
                class="cancel-btn" 
                @click="versionStore.showVersionCreator = false"
                :disabled="versionStore.loading"
              >
                取消
              </button>
              <button 
                type="submit" 
                class="submit-btn"
                :disabled="versionStore.loading"
              >
                {{ versionStore.loading ? '创建中...' : '创建' }}
              </button>
            </div>
          </form>
        </div>
      </div>
    </main>
  </div>
</template>

<style scoped>
.app-container {
  display: flex;
  min-height: 100vh;
  width: 100%;
}

.app-sidebar {
  width: 240px;
  background-color: #2c3e50;
  color: #ecf0f1;
  display: flex;
  flex-direction: column;
}

.sidebar-header {
  padding: 20px;
  border-bottom: 1px solid #34495e;
}

.sidebar-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.sidebar-header .version-selector {
  margin-top: 15px;
  padding: 10px;
  background-color: rgba(255,255,255,0.1);
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.sidebar-header .version-selector .label {
  font-size: 12px;
  color: #bdc3c7;
}

.sidebar-header .version-selector select {
  padding: 8px;
  border: 1px solid #34495e;
  border-radius: 4px 0 0 4px;
  background-color: #34495e;
  color: #ecf0f1;
  font-size: 14px;
  width: calc(100% - 32px);
}

.sidebar-header .version-selector .version-action-btn {
  padding: 8px 12px;
  border: 1px solid #34495e;
  color: #ecf0f1;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
}

.sidebar-header .version-selector .publish-version-btn {
  background-color: #4CAF50;
}

.sidebar-header .version-selector .publish-version-btn:hover:not(:disabled) {
  background-color: #3e8e41;
}

.sidebar-header .version-selector .new-version-btn {
  background-color: #3498db;
}

.sidebar-header .version-selector .new-version-btn:hover {
  background-color: #2980b9;
}

.sidebar-header .version-selector .version-action-btn:disabled {
  background-color: #95a5a6;
  cursor: not-allowed;
  opacity: 0.7;
}

.sidebar-header .version-selector .loading {
  font-size: 12px;
  color: #bdc3c7;
  text-align: center;
  padding: 8px 0;
}

.sidebar-nav {
  padding: 10px 0;
  flex-grow: 1;
  overflow-y: auto;
}

.nav-item, .nav-header {
  display: flex;
  align-items: center;
  padding: 12px 20px;
  color: #ecf0f1;
  text-decoration: none;
  transition: all 0.2s;
  cursor: pointer;
}

.nav-item:hover, .nav-header:hover {
  background-color: #34495e;
}

.nav-item.router-link-exact-active {
  background-color: #3498db;
}

.nav-item .icon, .nav-header .icon {
  margin-right: 10px;
  font-size: 16px;
}

.nav-item .text, .nav-header .text {
  flex-grow: 1;
}

.nav-header .arrow {
  font-size: 12px;
}

.nav-group {
  margin-bottom: 5px;
}


.nav-subitem {
  display: flex;
  align-items: center;
  padding: 10px 20px;
  font-size: 14px;
  color: #ecf0f1;
  text-decoration: none;
  cursor: pointer;
  transition: all 0.2s;
  background: none;
  border: none;
  width: calc(100% - 20px); /* 减去左边距 */
  margin-left: 20px; /* 与父栏目对齐 */
  box-sizing: border-box; /* 包含padding在宽度内 */
}

.nav-subitem:hover {
  background-color: #34495e;
}

.nav-subitem .icon {
  margin-right: 10px;
  font-size: 14px;
}

/* 移除不再使用的样式 */

.app-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background-color: #f5f7fa;
}
</style>

<style>
/* 全局样式 */
body {
  font-family: Arial, sans-serif;
  margin: 0;
  padding: 0;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  width: 400px;
  max-width: 90%;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
}

.modal-content h3 {
  margin-top: 0;
  color: #2c3e50;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
  color: #2c3e50;
}

.form-group input,
.form-group select,
.form-group textarea {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.form-group textarea {
  resize: vertical;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

.form-actions button {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.2s;
}

.submit-btn {
  background-color: #3498db;
  color: white;
}

.submit-btn:hover {
  background-color: #2980b9;
}

.submit-btn:disabled {
  background-color: #95a5a6;
  cursor: not-allowed;
}

.cancel-btn {
  background-color: #e74c3c;
  color: white;
}

.cancel-btn:hover {
  background-color: #c0392b;
}

.cancel-btn:disabled {
  background-color: #95a5a6;
  cursor: not-allowed;
}

.error-alert {
  position: fixed;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  background-color: #ffebee;
  border: 1px solid #ef9a9a;
  border-radius: 4px;
  padding: 10px 15px;
  z-index: 2000;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
  max-width: 80%;
}

.error-content {
  display: flex;
  align-items: center;
  gap: 10px;
}

.close-btn {
  background: none;
  border: none;
  font-size: 18px;
  cursor: pointer;
  color: #666;
}

.close-btn:hover {
  color: #333;
}
</style>
